/* ECE454 Project 1: server.c */
/* Acknowledgement: The socket part was implemented with the help of http://www.linuxhowtos.org/C_C++/socket.htm */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "./Peers.h"

#define FILEPATH "./localFile.txt"
#define WORD 4
#define CHARNUM 1000



void error( const char * msg)
{
	perror(msg);
	exit(1);
}

int main (int argc, char *argv[])
{
	int srvrSocket, cliSocket, portNo;
	socklen_t clientLen;
	char * addr;
	char buffer[256];
	struct sockaddr_in srvr_addr, cli_addr;
	int n;
	FILE *fp;	
	char *file;
	Peer p;	
	int insertStat = 0;	

	file = (char *) malloc(1000*sizeof(char));
	//fp = fopen(FILEPATH, "r");
	//fread(file, sizeof(char), CHARNUM, fp);
	//returnVal = p.insert("Peers.c");
	
	//printf("The value returned from Peers: %d\n", returnVal);

	if(argc < 2) {
		fprintf(stderr, "No Port Available!\n");
		exit(1);
	}	

	srvrSocket = socket(AF_INET, SOCK_STREAM, 0);

	if(srvrSocket < 0)
		error("ERROR opening socket");

	bzero( (char *) &srvr_addr, sizeof(srvr_addr) );
	portNo = atoi(argv[1]);
	
	printf("Port No is %d\n", portNo);
	srvr_addr.sin_family = AF_INET;
        srvr_addr.sin_addr.s_addr = INADDR_ANY;
	srvr_addr.sin_port = htons(portNo);

	if( bind( srvrSocket, (struct sockaddr *) &srvr_addr, sizeof(srvr_addr) ) < 0 )
		error("Error! on binding");
	
	printf("Server Socket: %s\n", srvr_addr.sin_addr.s_addr); 
	listen(srvrSocket, 5);
	clientLen = sizeof(cli_addr);
	
	printf("Waiting for Client!\n");
	cliSocket = accept( srvrSocket, (struct sockaddr *) &cli_addr, &clientLen ); 
	
	if(cliSocket < 0)
		error("Error! on accept");

	bzero(buffer, 256);
	// buffer now has name of the file that needs to be opened
	n = read(cliSocket, buffer, 255);

	if(n < 0)
		error("Error! in reading from the socket");
	
	insertStat = p.insert(FILEPATH, file);	
 	printf("Number of elements returned from Peer.h: %d", insertStat);
	
	//if(insertStat == CHARNUM) //fread function returns number of elements
		n= write(cliSocket, file, 255 );
	//else error("Error! in receiving file from Peer.h");

	if (n < 0)
		error("Error! in writing to socket");
	
	close(cliSocket);
	close(srvrSocket);
 	free(file);
	
	return 0;
}
